// pages/addressAdd/index.js
import {
  areaList
} from '@vant/area-data';
import Toast from '@vant/weapp/toast/toast';

import {
  getUserAddress
} from "../../api/address";

const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //vant默认的省市区数据 npm i @vant/area-data
    areaList,
    show: false, //省市区选择器弹出
    username: '',
    phonenumber: '',
    addressDetail: '',
    addressList: [], //用户收货地址列表
    address: '请选择地址',

  },
  //填写收货地址
  onConfirm: function (e) {
    const {
      values
    } = e.detail;
    console.log("确定省市区：", values)
    var address = ""
    for (let element of values) {
      if (element.name === undefined || element.name === "") {
        wx.showToast({
          title: '地址不完整！',
        })
        break; // 直接跳出循环
      }
      address += element.name;
    };
    this.setData({
      address: address,
      show: false,
    })
    console.log("省市区为：", address);
  },
  //点击弹出级联省市区选择器
  onClick: function () {
    this.setData({
      show: true
    })
  },
  //关闭级联省市区选择器
  onClose: function () {
    this.setData({
      show: false
    })
  },

  onShow() {
    getUserAddress().then((res) => {
      this.setData({
        addressList: res.data
      })
    })
  },
  bindKeyName: function (e) {
    this.setData({
      username: e.detail.value
    })
  },
  bindKeyMobile: function (e) {
    this.setData({
      phonenumber: e.detail.value
    })
  },
  bindKeyDetailed: function (e) {
    this.setData({
      addressDetail: e.detail.value
    })
  },
  //提交数据并发送到后台
  submit: function () {
    console.log(this.data);
    app.globalData.address = this.data.address + this.data.addressDetail;
    console.log(app.globalData.address)
    app.http('wechat/saveUserAddress', 'Post', {
      name: this.data.username,
      phoneNumber: this.data.phonenumber,
      address: this.data.addressDetail,
      isDefault: 1
    });

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

  /**
   * 打开地图
   */
  chooseAddress() {
    wx.chooseAddress({
      success: (res) => {
        let address = res.provinceName + res.cityName + res.countyName + res.detailInfo;
        let username = res.userName;
        let phonenumber = res.telNumber;
        console.log("联系人：" + username);
        console.log("手机号码：" + phonenumber);
        console.log("收货地址：" + address);
        this.setData({
          username: username,
          phonenumber: phonenumber,
          addressDetail: address
        })
      },
      fail: (res) => {
        console.log(res)
        console.log("收货地址获取失败，请手动输入地址！")
      },
      complete: (res) => {
        console.log('获取用户地址成功')
      }
    })
  }

})